package com.yhd.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yhd.gmall.common.constant.MqConst;
import com.yhd.gmall.common.service.RabbitService;
import com.yhd.gmall.model.enums.PaymentStatus;
import com.yhd.gmall.model.enums.ProcessStatus;
import com.yhd.gmall.model.order.OrderInfo;
import com.yhd.gmall.model.payment.PaymentInfo;
import com.yhd.gmall.order.service.OrderService;
import com.yhd.gmall.payment.client.PaymentFeignClient;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author yhd
 * @createtime 2020/10/2 11:21
 * 接收消息
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;



    /**
     * 扣减库存成功，更新订单状态
     * @param msgJson
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrderStatus(String msgJson, Message message, Channel channel) throws IOException {
        if (!StringUtils.isEmpty(msgJson)){
            Map<String,Object> map = JSON.parseObject(msgJson, Map.class);
            String orderId = (String)map.get("orderId");
            String status = (String)map.get("status");
            if ("DEDUCTED".equals(status)){
                // 减库存成功！ 修改订单状态为已支付
                orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);
            }else {
        /*
            减库存失败！远程调用其他仓库查看是否有库存！
            true:   orderService.sendOrderStatus(orderId); orderService.updateOrderStatus(orderId, ProcessStatus.NOTIFIED_WARE);
            false:  1.  补货  | 2.   人工客服。
         */
                orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void orderCancel(Long orderId, Message message , Channel channel){
        // 判断订单Id 是否为空！
        // 这里不止要关闭电商平台的交易记录，还需要关闭支付宝的交易记录。
        if (null!=orderId){
            // 为了防止重复消息这个消息。判断订单状态
            // 通过订单Id 来获取订单对象 select * from orderInfo where id = orderId
            OrderInfo orderInfo = orderService.getById(orderId);
            // 涉及到关闭orderInfo ,paymentInfo ,aliPay
            // 订单状态是未支付
            if (null!= orderInfo && orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.getOrderStatus().name())){
                // 关闭过期订单
                // orderService.execExpiredOrder(orderId);
                // 订单创建时就是未付款，判断是否有交易记录产生
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                if (null!=paymentInfo && paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                    // 先查看是否有交易记录 {用户是否扫了二维码}
                    Boolean aBoolean = paymentFeignClient.checkPayment(orderId);
                    if(aBoolean){
                        // 有交易记录 ，关闭支付宝 防止用户在过期时间到的哪一个瞬间，付款。
                        Boolean flag = paymentFeignClient.closePay(orderId);
                        if (flag){
                            // 用户未付款 ，开始关闭订单，关闭交易记录 2:表示要关闭交易记录paymentInfo 中有数据
                            orderService.execExpiredOrder(orderId,"2");
                        }else{
                            // 用户已经付款
                            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                                    MqConst.ROUTING_PAYMENT_PAY,orderId);
                        }
                    }else{
                        // 在支付宝中没有交易记录，但是在电商中有交易记录
                        orderService.execExpiredOrder(orderId,"2");
                    }
                }else {
                    // 也就是说在paymentInfo 中根本没有交易记录。
                    orderService.execExpiredOrder(orderId,"1");
                }
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
